﻿using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Localization;
using Microsoft.Extensions.Primitives;

namespace Jy.Abp.AspNetCore.Localization;

/// <summary>
/// 重写从http头获取语言，处理zh-CN\zh-HK等转zh-Hans\zh-Hant的转换
/// </summary>
public class DefaultAcceptLanguageHeaderRequestCultureProvider : AcceptLanguageHeaderRequestCultureProvider
{
    //语言对应区域
    public static Dictionary<string, string[]> LanguageAreas = new Dictionary<string, string[]>(){
        {"zh-Hant", new string[] { "zh-TW", "zh-MO", "zh-HK" }},
        {"zh-Hans", new string[] { "zh" }}
    };

    public DefaultAcceptLanguageHeaderRequestCultureProvider(RequestLocalizationOptions options)
    {
        Options = options;
    }

    public override async Task<ProviderCultureResult> DetermineProviderCultureResult(HttpContext httpContext)
    {
        var result = await base.DetermineProviderCultureResult(httpContext);
        if (result != null && !result.Cultures.IsNullOrEmpty())
            //如果指定的区域在定义的字典中，则添加字典中的语言
            foreach (var area in LanguageAreas)
            {
                var item = result.Cultures.FirstOrDefault(t => area.Value.Contains(t.Value));
                if (item == null || !item.HasValue)
                    continue;
                var index = result.Cultures.IndexOf(item);
                result.Cultures.Insert(index, new StringSegment(area.Key));
            }
        return result;
    }
}
